﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace HXDNB.DAL
{
    public class TemplateBLL : IDisposable
    {
        readonly Entities _e = new Entities();

        /// <summary>
        /// 查询所有模板
        /// </summary>
        public IEnumerable<Template> Select()
        {
            return _e.Templates.ToList();
        }

        /// <summary>
        /// 查询未发布模板
        /// </summary>
        public IEnumerable<Template> SelectNoReleaseTemplates()
        {
            return _e.Templates.Where(t => t.IsRelease == "N").ToList();
        }

        /// <summary>
        /// 根据ID查询模板
        /// </summary>
        public Template Get(int id)
        {
            return _e.Templates.FirstOrDefault(t => t.Id == id);
        }

        /// <summary>
        /// 根据Name查询模板
        /// </summary>
        public Template Get(string name)
        {
            return _e.Templates.FirstOrDefault(t => t.Name == name);
        }

        /// <summary>
        /// 添加模板信息
        /// </summary>
        public int Add(Template temp)
        {
            try
            {
                temp.Type = "1";
                _e.Templates.AddObject(temp);
                _e.SaveChanges();
            }
            catch (Exception)
            {
                temp.Id = 0;
            }

            return temp.Id;
        }

        /// <summary>
        /// 修改模板信息
        /// </summary>
        public bool Edit(Template temp)
        {
            try
            {
                temp.Type = "1";
                _e.Templates.Attach(temp);
                _e.ObjectStateManager.ChangeObjectState(temp, EntityState.Modified);
                return _e.SaveChanges() > 0;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 删除模板信息
        /// </summary>
        public bool Delete(int id)
        {
            try
            {
                var info = Get(id);
                if (info == null)
                    return false;
                _e.Templates.DeleteObject(info);
                return _e.SaveChanges() > 0;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public void Dispose()
        {
            GC.SuppressFinalize(this);
        }
    }
}
